package com.duang.netty.agreement.server;
import com.duang.netty.agreement.utils.NettyMessageDecoder;
import com.duang.netty.agreement.utils.NettyMessageEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

public class NettyServer {
    public void bind(String host,int port) throws InterruptedException {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss,work).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,100)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline p = socketChannel.pipeline();
                        p.addLast(new NettyMessageDecoder(1024*1024,4,4,-8,0));
                         p.addLast(new NettyMessageEncoder());
                         p.addLast(new ReadTimeoutHandler(50));
                         p.addLast(new LoginAuthRespHandler());
                         p.addLast(new HeartBeatRespHandler());
                    }
                });
        ChannelFuture future = b.bind(host,port).sync();
        System.out.println("Netty Server start ok !" );
    }

    public static void main(String[] args) throws Exception {
        new NettyServer().bind("127.0.0.1",9999);
    }
}
